package validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.ForgotPasswordForm;

@Component
public class ForgotPasswordValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return ForgotPasswordForm.class.equals(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		ForgotPasswordForm form = (ForgotPasswordForm) target;
		if(form.getUserName() == null ) {
			errors.rejectValue("userName", "empty");
		} else if(form.getUserName().isEmpty()) {
			errors.rejectValue("userName", "empty");
		}
		if(form.getEmail() == null ) {
			errors.rejectValue("email", "empty");
		}else if(form.getEmail().isEmpty()) {
			errors.rejectValue("email", "empty");
		}else {
			if(!form.getEmail().matches("^[\\w\\-\\_\\+]+(\\.[\\w\\-\\_]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$")){
				errors.rejectValue("email", "invalid");
			}else if(form.getEmail().length()>100){
				errors.rejectValue("email", "tooLong");
			}
		}
	}
}